package xyz.xtt.exchange.utils;

import cn.hutool.core.io.FileUtil;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author xugaopeng
 * @date 2024-12-12-18:50
 */
@Slf4j
@RefreshScope
@Component
public class CosFileUtil {
    @Value("${oss.tengxun.region}")
    private String reg;
    @Value("${oss.tengxun.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.tengxun.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.tengxun.bucketName}")
    private String bucketName;

    private volatile static COSClient cos;


    public String uploadFileToCos(File file, String key) {
        StringBuilder st = new StringBuilder(key);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
        st.append(sf.format(new Date()));
        st.append("/"+UuidUtils.generateUuid()).append("."+FileUtil.getSuffix(file));
        initCOSClient();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, st.toString(), file);
        PutObjectResult putObjectResult = cos.putObject(putObjectRequest);
        log.info("上传图片的路径为：{}",st.toString());
        return st.toString();
    }

    private void initCOSClient() {
        if (cos == null) {
            synchronized (CosFileUtil.class) {
                if (cos == null) {
                    COSCredentials cred = new BasicCOSCredentials(accessKeyId, accessKeySecret);
                    // 2 设置 bucket 的地域
                    // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分
                    Region region = new Region(reg); //COS_REGION 参数：配置成存储桶 bucket 的实际地域，例如 ap-beijing，更多 COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
                    ClientConfig clientConfig = new ClientConfig(region);
                    // 3 生成 cos 客户端
                    clientConfig.setHttpProtocol(HttpProtocol.https);
                    cos = new COSClient(cred, clientConfig);
                }
            }
        }
    }
}
